package com.song.admin.controller;

import com.song.admin.service.CategoryService;
import com.song.api.BaseController;
import com.song.api.controller.admin.CategoryMngControllerApi;
import com.song.grace.result.GraceJSONResult;
import com.song.grace.result.ResponseStatusEnum;
import com.song.pojo.Category;
import com.song.pojo.bo.SaveCategoryBO;
import com.song.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
public class CategoryMngController extends BaseController implements CategoryMngControllerApi {

    @Autowired
    private CategoryService categoryService;

    private static final Logger LOG = LoggerFactory.getLogger(CategoryMngController.class);

    @Override
    public GraceJSONResult saveOrUpdateCategory(@Valid SaveCategoryBO saveCategoryBO) {


        Category newCat = new Category();
        BeanUtils.copyProperties(saveCategoryBO, newCat);
        // id为空新增，不为空修改
        LOG.info(saveCategoryBO.getOldName());

        if (saveCategoryBO.getId() == null) {
            // 查询新增的分类名称不能重复存在
            boolean isExist = categoryService.queryCatIsExist(newCat.getName(), null);
            if (!isExist) {
                // 新增到数据库
                categoryService.createCategory(newCat);
            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        } else {
            // 查询修改的分类名称不能重复存在
            boolean isExist = categoryService.queryCatIsExist(newCat.getName(), saveCategoryBO.getOldName());
            if (!isExist) {
                // 修改到数据库
                categoryService.modifyCategory(newCat);
            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.CATEGORY_EXIST_ERROR);
            }
        }
        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult getCatList() {
        List<Category> category = categoryService.getCategory();
        return GraceJSONResult.ok(category);
    }

    @Override
    public GraceJSONResult getCats() {

        // 0.查询判断redis中是否包含信息，如果包含，则查询后直接返回，就不去查询数据库了
        String allCatJson = redis.get(REDIS_ALL_CATEGORY);
        List<Category> category = null;
        if (StringUtils.isBlank(allCatJson)) {
            category = categoryService.getCategory();
            redis.set(REDIS_ALL_CATEGORY, JsonUtils.objectToJson(category));
        }else {
            category = JsonUtils.jsonToList(allCatJson,Category.class);
        }

        return GraceJSONResult.ok(category);
    }

}
